<?php
/*
	服务公司：沧州讯呗网络科技有限公司
	作者：sun
*/
namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Repositories\UsersRepository;
use Illuminate\Http\Request;
use App\Traits\Weixin;
use App\Traits\BaseFun;
use App\Models\Users;

class LoginController extends Controller
{
    public function __construct(
        UsersRepository $UsersRepository

    ) {
        $this->UsersRepository = $UsersRepository;
    }

    public function getOpenid(Request $request)
    {
        $res=Weixin::getOpenId($request);
        if ($res) {
           $ArrDate = ['state' => 0, 'data' => $res, 'token' => $request->input('token')];
        }else{
           $ArrDate = ['state' => 2, 'data' => $res, 'msg' => '获取失败']; 
        }
        return BaseFun::jsonReturn($ArrDate);
    }

    public function login(Request $request)
    {
        $openid = $request->input('openid');
        $userInfo = $this->UsersRepository->info(['openid' => $openid]);
        $dataArr = [];
        $Token = md5(time() . rand(1000, 9999));
        if ($userInfo) {
            if ($userInfo['login_token'] == null) {
                $login_token = Users::where('id', $userInfo['id'])->update(['login_token' => $Token, 'token_time' => time()]);
            }

            if ($userInfo['state'] == 2) {
                $dataArr['msg'] = '已封号';
                $dataArr['data'] = $userInfo;
                $dataArr['state'] = 2;
            } else {

                if ($request->avatar) {
                    $userin = Users::where('id', $userInfo['id'])->update(['login_token' => $Token,'avatar' => $request->avatar, 'nickname' => $request->nickname]);
                }
                $dataArr['token'] =$Token;
                $dataArr['data'] = $userInfo;
                $dataArr['state'] = 0;                                    
            }
            return BaseFun::jsonReturn($dataArr);
        } else {
            $userInfo = $this->UsersRepository->create($request->all());
            $Token = md5(time() . rand(1000, 9999));
            $login_token = Users::where('id', $userInfo['id'])->update(['login_token' => $Token, 'token_time' => time()]);
            $dataArr['token'] = $Token;
            $dataArr['data'] = $userInfo;
            $dataArr['state'] = 0;
            return BaseFun::jsonReturn($dataArr);
        }
    }


}
